<?php

require_once LIBRARIES_ENTITIES_DATABASE;
require_once LIBRARIES_ENTITIES_CATEGORIES;
require_once LIBRARIES_ENTITIES_ITEMS;
require_once LIBRARIES_ENTITIES_ITEMPROPERTIES;
require_once LIBRARIES_TOOLS_XTEMPLATE;
require_once LIBRARIES_TOOLS_UTILITY;

class ComSearchController {

    public function invoke() {

        $action = '';
        if (isset($_POST['hdAction'])) {
            $action = $_POST['hdAction'];
        }

        $searchType = '';
        if (isset($_GET['hdSearchType'])) {
            $searchType = $_GET['hdSearchType'];
        }

        $searchText = '';
        if (isset($_GET['txtSearch'])) {
            $searchText = $_GET['txtSearch'];
        }




        if ($action == 'searchItem') {

            // kiểm tra có chức năng đặt hàng không, nếu có thì hiển thị nút đặt hàng và các thông tin liên qua
            $configuration = new Configuration();
            $xmlFile = ROOT . DS . 'configuration.xml';
            $configuration->getConfiguration($xmlFile);
            $isSalse = false;
            if ($configuration->getSales() == 1) {
                $isSalse = true;
            }


            $searchText = $_POST['txtSearch'];



            $price = $_POST['slPrice'];


            $propertyValue = $_POST['slProperties'];



            $derectory = dirname(__FILE__);




            $xtemplate = new XTemplate($derectory . DS . 'views' . DS . 'search.html');



//            $string = "tôi muốn 'là' người giỏi nhất. kiếm\b tiền nhiều nhất";
//
//            $array = $this->search_split_terms($string);
//
//            echo $string;
//            echo '<hr/>';
//
//
//
//
//            echo '<pre>';
//            var_dump($array);
//            echo '</pre>';
//            echo '<hr/>';
//
//
//
//            $terms_db = $this->search_db_escape_terms($array);
//
//            echo '<pre>';
//            var_dump($terms_db);
//            echo '</pre>';
//
//
//
//
//            $results = $this->search_perform($string);
//            $term_list = $this->search_pretty_terms($this->search_html_escape_terms($this->search_split_terms($string)));
//
//
//
//
//            $smarty->assign('term_list', $term_list);
//
//            if (count($results)) {
//
//                $smarty->assign('results', $results);
//                $smarty->display('search_results.txt');
//            } else {
//
//                $smarty->display('search_noresults.txt');
//            }
//
//
//
//
//
//            exit();
            // search item
            $articles = $this->searchItem($searchText, $price, $propertyValue);

            if (count($articles) > 0) {

                $itemList_HTML = '';

                // loop each item
                for ($y = 0; $y < count($articles); $y++) {

                    if ($articles[$y]->getState() == 1) {

                        // get days between createdDate and current date
                        $daysBetweenDate = Utility::daysBetweenDate($articles[$y]->getCreatedDate(), Utility::getCurrentDate());

                        // if days = 0 and days <= 3 then show new icon
                        if ($daysBetweenDate <= 3) {
                            $xtemplate->parse('main.item_list.new_icon');
                        }

                        $xtemplate->assign('ITEM_ID', $articles[$y]->getID());
                        $xtemplate->assign('ITEM_ALIAS', $articles[$y]->getAlias());
                        $xtemplate->assign('ITEM_IMAGE', $articles[$y]->getImage());
                        $xtemplate->assign('ITEM_NAME', $articles[$y]->getName());
                        $xtemplate->assign('ITEM_PRICE', Utility::formatToCurrencyString($articles[$y]->getPrice()));

                        if ($isSalse) {
                            $xtemplate->parse('main.item_list.price');
                            $xtemplate->parse('main.item_list.add_to_cart_button');
                        }

                        $xtemplate->parse('main.item_list');
                    }
                }
            }

            $xtemplate->parse('main');
            $xtemplate->out('main');
            exit();
        } else if ($action == 'searchArticle') {



            $searchText = $_POST['txtTextSearch'];


            $derectory = dirname(__FILE__);




            $xtemplate = new XTemplate($derectory . DS . 'views' . DS . 'search.html');


            // search item
            $articles = $this->searchArticle($searchText);


            if (count($articles) > 0) {

                $itemList_HTML = '';

                // loop each item
                for ($y = 0; $y < count($articles); $y++) {

                    if ($articles[$y]->getStatus() == 1) {

                        $xtemplate->assign('ARTICLE_ID', $articles[$y]->getID());
                        $xtemplate->assign('ARTICLE_TITLE', $articles[$y]->getTitle());
                        $xtemplate->assign('ARTICLE_IMAGE', $articles[$y]->getImage());
                        $xtemplate->assign('ARTICLE_ALIAS', $articles[$y]->getAlias());
                        $xtemplate->assign('ARTICLE_DATE', Utility::formatDateTimeToView($articles[$y]->getModifiedDate()));

                        $xtemplate->assign('ARTICLE_DESCRIPTION', $articles[$y]->getDescription());

                        if($articles[$y]->getImageStatus()==1){
                            $xtemplate->parse('main.article_list.article_image');
                        }
                        $xtemplate->parse('main.article_list');
                    }
                }
            }

            $xtemplate->parse('main');
            $xtemplate->out('main');
            exit();
        }







        $derectory = dirname(__FILE__);
        $xtemplate = new XTemplate($derectory . DS . 'views' . DS . 'search.html');
        $xtemplate->assign('SEARCH_TEXT', $searchText);
        $this->fillSelectBox_Properties($xtemplate, 'main.layout.property_list');
        $xtemplate->parse('main.layout');
        $xtemplate->parse('main.javascript');
        $xtemplate->parse('main');
        $xtemplate->out('main');
    }

    // get list of item by a category id
    private function searchItem($searchText, $price, $propertyValue) {
        $db = new Database();
        try {
            $item = new Items();
            $item->setName($searchText);
            $item->setPrice($price);
            $result = $item->search($db, $propertyValue);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo "getItemList error: " . $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function getDistinctItemProperty() {
        $db = new Database();
        try {
            $itemProperty = new ItemProperties();
            $result = $itemProperty->getListGroupByValue($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo "error: " . $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function fillSelectBox_Properties($xtemplate, $block) {

        $itemProperties = $this->getDistinctItemProperty();
        if (count($itemProperties) > 0) {
            for ($i = 0; $i < count($itemProperties); $i++) {
                $xtemplate->assign('PROPERTY_NAME', $itemProperties[$i]->getProperty()->getName());
                $xtemplate->assign('PROPERTY_VALUE', $itemProperties[$i]->getValue());
                $xtemplate->parse($block);
            }
        }
    }

    // get list of item by a category id
    private function searchArticle($searchText) {
        $db = new Database();
        try {
            $article = new Articles();
            $result = $article->search($db, $searchText);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo "getItemList error: " . $exc->getMessage();
            $db->rollback();
            exit();
        }
    }


    
    
    
    
    

    // function search_perform($terms) {

    //     // chạy hàm tách câu thành mảng ký tự riêng biệt
    //     $terms = $this->search_split_terms($terms);

    //     // make sure each term matches on word boundaries
    //     $terms_db = $this->search_db_escape_terms($terms);


    //     $terms_rx = $this->search_rx_escape_terms($terms);

    //     $parts = array();
    //     foreach ($terms_db as $term_db) {
    //         $parts[] = "A_Content RLIKE '$term_db'";
    //     }
    //     $parts = implode(' AND ', $parts);

    //     $sql = "SELECT * FROM Content WHERE $parts";

    //     $rows = array();

    //     $result = mysql_query($sql);
    //     while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

    //         $row[score] = 0;

    //         foreach ($terms_rx as $term_rx) {
    //             $row[score] += preg_match_all("/$term_rx/i", $row[content_body], $null);
    //         }

    //         $rows[] = $row;
    //     }

    //     uasort($rows, 'search_sort_results');

    //     return $rows;
    // }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    function search_sort_results($a, $b) {

        $ax = $a[score];
        $bx = $b[score];

        if ($ax == $bx) {
            return 0;
        }
        return ($ax > $bx) ? -1 : 1;
    }

    function search_html_escape_terms($terms) {
        $out = array();

        foreach ($terms as $term) {
            if (preg_match("/\s|,/", $term)) {
                $out[] = '"' . HtmlSpecialChars($term) . '"';
            } else {
                $out[] = HtmlSpecialChars($term);
            }
        }
        return $out;
    }

    function search_pretty_terms($terms_html) {

        if (count($terms_html) == 1) {
            return array_pop($terms_html);
        }

        $last = array_pop($terms_html);

        return implode(', ', $terms_html) . " and $last";
    }

}

?>
